﻿using System;
using System.Linq;
using System.Web;
using umbraco;
using umbraco.BusinessLogic;

namespace TheOutfield.UmbExt.Backfire4Umbraco.Web
{
    public class BackfireModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        { }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        protected void context_BeginRequest(object sender, EventArgs e)
        {
            var httpApp = sender as HttpApplication;
            if (httpApp != null)
            {
                var resolvedUmbracoPath = GlobalSettings.Path.Replace("~/", httpApp.Request.ApplicationPath).ToLower();
                if(httpApp.Context.IsDebuggingEnabled && !httpApp.Request.Path.ToLower().Contains(resolvedUmbracoPath))
                {
                    var currentUser = User.GetCurrent();

                    if(currentUser != null && currentUser.Applications != null && currentUser.Applications.Length > 0 && currentUser.Applications.Any(app => app.alias == "settings"))
                    {
                        httpApp.Response.Filter = new BackfireFilter(httpApp.Response.Filter);
                    }
                }
                
            }
        }

        #endregion
    }
}
